//
//  BaseSheetView.swift
//  HomeFurnishing
//
//  Created by 智蚂优服 on 2019/1/4.
//  Copyright © 2019 智蚂优服. All rights reserved.

import UIKit
import TZImagePickerController
import MobileCoreServices
class ZMSelectImage: UIView, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        
    private var maxCount = 0
    private var dataSouce = [["拍照", "相册"], ["取消"]]
    private var video = false
    private var assets = [Any]()
    private var selectImg = [UIImage]()
    private var selectImageBlock: ((_ photos: [UIImage], _ assets: [Any]) -> ())?
    
    // 弹框：相册，相机选项
    public class func show(_ maxCount: Int, _ video: Bool = false, _ selectImg: [UIImage] = [], _ assets: [Any] = [], _ block: ((_ photos: [UIImage], _ assets: [Any]) -> ())?) {
        let view = ZMSelectImage()
        if video {
            view.dataSouce[0][0] = "拍摄"
        }
        view.backgroundColor = UIColor.zm.color(hexString: "#000000", 0.65)
        view.selectImg = selectImg
        view.assets = assets
        view.video = video
        view.frame = SCREEN_BOUNDS
        view.selectImageBlock = block
        view.maxCount = maxCount
        view.addSubview(view.mainTable)
        view.mainTable.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(147 + BottomSpace)
        }
        APPWindow?.addSubview(view)
    }
    
    /// 直接选择相册
    public class func select(_ maxCount: Int, _ selectImg: [UIImage] = [], _ assets: [Any] = [], _ block: ((_ photos: [UIImage], _ assets: [Any]) -> ())?) {
        let view = ZMSelectImage()
        view.maxCount = maxCount
        view.selectImageBlock = block
        UIApplication.zm.visibleViewController().present(view.tzPickerVC, animated: false, completion: nil)
        view.tzPickerVC.didFinishPickingPhotosHandle = {(photos, assets, isSelectOriginalPhoto) in
            view.selectImgSuccess(photos: photos!, assets: assets!)
        }
    }
        
    // MARK: - Getters and Setters
    lazy var imagePickerVC: UIImagePickerController = {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .camera
        picker.modalPresentationStyle = .currentContext
        picker.mediaTypes = (video ? ["\(kUTTypeMovie)"] : ["\(kUTTypeImage)"])
        picker.videoMaximumDuration = 30
        return picker
    }()
    
    lazy var tzPickerVC: TZImagePickerController = {
        let vc = TZImagePickerController(maxImagesCount: maxCount, columnNumber: 4, delegate: self)
        vc!.allowTakeVideo = false
        vc!.allowPickingOriginalPhoto = false
        vc!.allowTakePicture = false
        vc!.autoDismiss = false
        vc!.allowPickingGif = false
        vc!.allowPickingVideo = video
        vc!.allowPickingImage = !video
        vc!.videoMaximumDuration = 10
//        if video {
//            vc?.allowPickingImage = false
//            vc?.videoMaximumDuration = 30
//            vc!.allowPickingVideo = true
//        }
        if assets.count > 0 {
            vc!.selectedAssets = NSMutableArray(array: assets)
        }
        vc!.imagePickerControllerDidCancelHandle = {
            vc?.dismiss(animated: false, completion: nil)
        }
        return vc!
    }()
        
    lazy var mainTable: UITableView = {
        let table = UITableView()
        table.backgroundColor = .white
        table.separatorInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
        table.separatorColor = UIColor.zm.color(hexString: "#000000", 0.1)
        table.isScrollEnabled = false
        table.delegate       = self
        table.dataSource     = self
        table.layer.cornerRadius = 8.0
        table.layer.masksToBounds = true
        table.register(UITableViewCell.self, forCellReuseIdentifier: "ZMSelectImageCell")
        return table
    }()
}


// MARK: - UITableViewDelegate, UITableViewDataSource
extension ZMSelectImage: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSouce.count
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSouce[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 0.01 : 3
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.zm.color(hexString: "#000000", 0.5)
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44.0
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ZMSelectImageCell", for: indexPath)
        cell.selectionStyle  = .none
        cell.backgroundColor = .white
        cell.textLabel?.text = dataSouce[indexPath.section][indexPath.row]
        cell.textLabel?.textAlignment = .center
        cell.textLabel?.font = UIFont.zm.fontRegular(size: 16)
        cell.textLabel?.textColor = UIColor.zm.color333333()
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                if selectImg.count == maxCount {
                    ZMToast.showToast(title: "最多\(maxCount)张图片")
                    return
                }
                UIApplication.zm.visibleNavigationController().present(self.imagePickerVC, animated: false, completion: nil)
            } else if indexPath.row == 1 {
                UIApplication.zm.visibleViewController().present(self.tzPickerVC, animated: false, completion: nil)
                if video {
                    self.tzPickerVC.didFinishPickingVideoHandle = { [unowned self] (photos, assets) in
                        self.selectImgSuccess(photos: [photos!], assets: [assets!])
                    }
                } else {
                    self.tzPickerVC.didFinishPickingPhotosHandle = {(photos, assets, isSelectOriginalPhoto) in
                        self.selectImgSuccess(photos: photos!, assets: assets!)
                    }
                }
            }
        }
        self.isHidden = true
    }
        
    func selectImgSuccess(photos: [UIImage], assets: [Any]) {
        tzPickerVC.dismiss(animated: false, completion: nil)
        guard let block = selectImageBlock else {return}
        block(photos, assets)
        self.removeFromSuperview()
    }
}

// MARK: -  UIImagePickerControllerDelegate
extension ZMSelectImage: TZImagePickerControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: false, completion: nil)
        guard let type = (info[UIImagePickerController.InfoKey.mediaType] as? String), type != "" else {
            return
        }
        
        if type == "public.image" {
            let image = (info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
            let tzImagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self)
            tzImagePickerVc?.showProgressHUD()
            let meta = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerMediaMetadata")] as! [String: Any]
            TZImageManager().savePhoto(with: image, meta: meta, location: nil) { [unowned self] (asset, error) in
                if error != nil {
                    ZMLog(message: "图片保存失败")
                } else {
                    if let assetModel = TZImageManager().createModel(with: asset) {
                        self.selectImg.append(image)
                        self.assets.append(assetModel.asset as Any)
                        guard let block = self.selectImageBlock else {return}
                        block(self.selectImg, self.assets)
                        self.removeFromSuperview()
                    }
                }
            }
        } else if type == "public.movie" {
            if let videoUrl = (info[UIImagePickerController.InfoKey.mediaURL] as? URL) {
                TZImageManager().saveVideo(with: videoUrl) { (asset, error) in
                    if error != nil {
                        ZMToast.showToast(title: "视频保存失败")
                    } else {
                        if let assetModel = TZImageManager().createModel(with: asset) {
                            TZImageManager().getPhotoWith(assetModel.asset) { (photo, info, isDegraded) in
                                if (!isDegraded && (photo != nil)) {
                                    self.selectImg.append(photo!)
                                    self.assets.append(assetModel.asset as Any)
                                    guard let block = self.selectImageBlock else {return}
                                    block(self.selectImg, self.assets)
                                    self.removeFromSuperview()
                                }
                            }
                        }
                    }
                }
            }
        }
        
    }

}
